﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Trentacular.SharePoint.Util;

namespace Trentacular.SharePoint.FeatureReceivers
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation,
    /// installation, uninstallation, and upgrade.
    /// </summary>
    public class CentralAdminExtensionsFeatureReceiver
        : BaseFeatureReceiver<SPWebApplication>
    {
        public override void FeatureActivated(
            SPWebApplication webApp,
            SPFeatureReceiverProperties properties
            )
        {
            if (!webApp.IsAdministrationWebApplication)
                throw new InvalidOperationException(
                    "The Central Administration Extensions Feature can only be activated on the Web Application hosting Central Administration"
                    );

            foreach (SPSite site in webApp.Sites)
            {
                var rootWeb = site.RootWeb;
                if (rootWeb.IsCentralAdmin())
                    rootWeb.Features.EnsureActivated(Config.CentralAdminCustomActionsFeatureID);
            }
        }

        public override void FeatureDeactivating(
            SPWebApplication webApp,
            SPFeatureReceiverProperties properties
            )
        {
            foreach (SPSite site in webApp.Sites)
            {
                var rootWeb = site.RootWeb;
                if (rootWeb.IsCentralAdmin())
                    rootWeb.Features.Remove(Config.CentralAdminCustomActionsFeatureID);
            }
        }
    }
}
